package com.yeskery.nut.cloud.registry.nacos;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.yeskery.nut.application.ServerEventContext;
import com.yeskery.nut.bean.ApplicationContext;
import com.yeskery.nut.bean.aware.ApplicationContextAware;
import com.yeskery.nut.cloud.registry.core.*;
import com.yeskery.nut.core.Environment;

import java.util.Collection;

/**
 * Nacos服务注册器
 * @author YESKERY
 * 2024/1/12
 */
public class NacosServerRegistry extends DefaultServerRegistry implements ApplicationContextAware {

    /** Nacos服务对象 */
    private NamingService namingService;

    /** 应用上下文 */
    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public void afterStart(ServerEventContext serverEventContext) {
        namingService = applicationContext.getBean(NamingService.class);
        Environment environment = applicationContext.getBean(Environment.class);
        ServerMetadata serverMetadata = getCurrentServerMetadata(environment);
        ServerInstanceMetadata serverInstanceMetadata = getCurrentServerInstanceMetadata(environment);

        try {
            namingService.registerInstance(serverMetadata.getName(), serverInstanceMetadata.getIp(), serverInstanceMetadata.getPort());
        } catch (NacosException e) {
            throw new RegistryException("Nacos Server Instance Register Fail.", e);
        }
    }

    @Override
    public void beforeClose(ServerEventContext serverEventContext) {
        super.beforeClose(serverEventContext);
        if (namingService != null) {
            try {
                namingService.shutDown();
            } catch (NacosException e) {
                throw new RegistryException("Nacos Client Close Fail.", e);
            }
        }
    }

    @Override
    public Server getServer(String name) {
        NacosServerInstanceRegistry nacosServerInstanceRegistry = new NacosServerInstanceRegistry(namingService);
        NacosServer nacosServer = new NacosServer();
        nacosServer.setId(name);
        nacosServer.setName(name);
        nacosServer.setServerInstanceRegistry(nacosServerInstanceRegistry);
        nacosServerInstanceRegistry.setServer(nacosServer);
        return nacosServer;
    }

    @Override
    public Collection<Server> getServers() {
        throw new RegistryException("UnSupport Obtain All Servers.");
    }

    @Override
    public Server registerServer(ServerMetadata metadata) {
        return getServer(metadata.getName());
    }

    @Override
    public void removeServer(String name) {
        throw new RegistryException("UnSupport Proactively Remove.");
    }
}
